<?php

namespace App\Jobs;

use App\Models\Star;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

//implements ShouldQueue
class DeleteStar
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 60;

    public $tries = 2;

    private $type;
    private $entity_id;
    private $user_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($type, $entity_id, $user_id = 0)
    {
        $this->type = $type;
        $this->entity_id = $entity_id;
        $this->user_id = $user_id;
    }


    public function handle()
    {
        \Log::info("==============start delete star job =========================");
        $model = Star::where('type', $this->type)->where('entity_id', $this->entity_id);
        $total = $model->count();

        if ($this->user_id)
            User::where('id', $this->user_id)->increment('stared_count', -$total);

        (clone $model)->chunk(100, function ($list) {
            $arr_user_id = array_column($list->toArray(), 'user_id');
            User::whereIn('id', $arr_user_id)->increment('star_count', -1);
        });
        (clone $model)->delete();
        \Log::info("==============end delete star job ============================");
    }
}
